package com.ronan.imserver.listener;

import com.ronan.common.constant.Constants;
import com.ronan.common.pojo.NettyInfo;
import com.ronan.imserver.service.RedisService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.context.event.ApplicationReadyEvent;
import org.springframework.context.ApplicationEvent;
import org.springframework.context.ApplicationListener;
import org.springframework.context.event.ContextClosedEvent;
import org.springframework.stereotype.Component;

import java.net.InetAddress;
import java.net.UnknownHostException;

/**
 * FileName    : com.ronan.imserver.utils
 * Description : 应用监听
 *
 * @author : ronan
 * @version : 1.0
 * Create Date : 2021/3/8 17:19
 **/
@Slf4j
@Component
public class IApplicationListener implements ApplicationListener {

    @Value("${rim.server.port}")
    private int port;

    @Value("${spring.application.name}")
    private String name;

    @Autowired
    private RedisService redisService;

    private NettyInfo nettyInfo;

    @Override
    public void onApplicationEvent(ApplicationEvent applicationEvent) {
        if (applicationEvent instanceof ApplicationReadyEvent) {
            log.info("服务启动,将im-server服务的ip:port保存到redis");
            String host = null;
            try {
                host = InetAddress.getLocalHost().getHostAddress();
            } catch (UnknownHostException e) {
                e.printStackTrace();
            }
            log.info("{}:启动,地址:{}:{}", name, host, port);
            NettyInfo info = new NettyInfo();
            info.setHost(host);
            info.setPort(port);
            this.nettyInfo = info;
            // 添加到redis中
            redisService.sAdd(Constants.NETTY_INFO_PREFIX, nettyInfo);
        } else if (applicationEvent instanceof ContextClosedEvent) {
            log.info("服务销毁时,从redis删除im-server服务的ip:port!");
            // 服务销毁时
            redisService.sRemove(Constants.NETTY_INFO_PREFIX, nettyInfo);

        }
    }
}
